var Cache = require('jsoncache');
var cache = new Cache({ dir: './cache', life: 60*60*1000, mode: 'json' });
var logger = require('../libs/log');
var tools = require('../libs/tools');
var then = require('thenjs');
var Baidu = {}

/*
 * 搜索日志对应的百度关键词是否已经存在 日志－>关键词
 * @param {Object} logData log日志
*/
Baidu.cacheLog = function (logData) {
	var eqid = tools.getQueryString('eqid',logData['referer']);
	var urlid = tools.getQueryString('url',logData['referer']);
	var wd = tools.getQueryString('wd',logData['referer']);
	if(!wd){
		wd = tools.getQueryString('word',logData['referer']);
	}
	var logKey = 'log_'+eqid+'_'+urlid;
	var kwKey = 'kw_'+eqid+'_'+urlid;
	console.info('referer:',logData['referer'])
	console.info('cacheLog logKey:',logKey);
	if(wd){
		console.info('wd!!!!!!!!!!!!!:',wd);
		logData['isPay']=true;
		Baidu.writeLog(logData,wd,'Baidu SEM');
		return;
	}
	if(!urlid){
		console.info('urlid:',urlid,'eqid:',eqid);
		Baidu.writeLog(logData,'','not baidu search');
		return;
	}
	then(function (defer) {
		cache.get(kwKey,function (err,doc) {
			if(err||!doc){
				defer(null,false);
			}else{
				defer(null,doc);
			}
		});
	}).then(function (defer,cacheDoc) {
		// console.info('cacheDoc:',cacheDoc);
		if(cacheDoc){
			Baidu.writeLog(logData,cacheDoc['query'],'cacheLog');
		}else{
			cache.set(logKey,logData,defer);
		}
	})
}

/*
 * 搜索百度关键词对应的日志是否已经存在 关键词－>日志
 * @param {String} 对应的url
 * https://www.baidu.com/link?url=aSVymxWNotQlcGBIu1uTlsaWTVJ5nKvoWpEQVyxHvHW&wd=%E7%89%9B%E5%95%86%E7%BD%91&eqid=92b10b8e0029650b000000025758d79c
 * @param {String} query 搜索的关键词
*/
Baidu.getLogData = function (referer,_query) {
	var eqid = tools.getQueryString('eqid',referer);
	var urlid = tools.getQueryString('url',referer);
	var query = tools.getQueryString('wd',referer);
	query = query || _query;
	var logKey = 'log_'+eqid+'_'+urlid;
	var kwKey = 'kw_'+eqid+'_'+urlid;
	console.info('getLogData logKey:',logKey);
	then(function (defer) {
		cache.get(logKey,function (err,doc) {
			if(err||!doc){
				defer(null,false);
			}else{
				defer(null,doc);
			}
		});
	}).then(function (defer,logData) {
		if(logData&&logData['time']){
			cache.set(logKey,{},defer);
			Baidu.writeLog(logData,query,'getLogData');
		}else{
			cache.set(kwKey,{query:query},defer);
		}
	})
}

Baidu.writeLog = function (logData,query,from) {
	logData['query'] = query;
	logger.logger(logData);
	console.info('writeLog for baidu query:',query,'; from:',from);
}
module.exports = Baidu
